package gripper.ftp.handle;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

import gripper.ftp.FtpSession;
import gripper.ftp.PathConvert;

public class MFMTHandle implements Handle {
	FtpSession ftpSession;
	static SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMddHHmmss");
	public MFMTHandle(FtpSession ftpSession) {
		this.ftpSession = ftpSession;
	}

	public void process(String line, BufferedReader br, OutputStream os) throws IOException {
		String[] splited = line.split(" ");
		if (splited == null || splited.length < 3) {
			os.write("550 requested action aborted.\r\n".getBytes());
			os.flush();
			return;
		}
		String fileName = splited[2].trim();
		String time = splited[1].trim();
		fileName = ftpSession.currentDir + "/" + fileName;
		fileName = PathConvert.toServerPath(ftpSession.getRootDir(), fileName);
		File file = new File(fileName);
		Date dt=new Date();
		try{
			dt=sdf.parse(time);
		}catch(Exception e){
			os.write("550 Invalid argument to date encode.\r\n".getBytes());
			os.flush();
			return;
		}
		if(!file.exists()){
			os.write("550 file not exist.\r\n".getBytes());
			os.flush();
			return;
		}
		file.setLastModified(dt.getTime());
		os.write("213 - Command successful.\r\n".getBytes());
	}

}
